<template>
	<view class="page">
		<div class="search-wrap">
			<!-- <div class="input">
				<input type="text" maxlength="10" v-model="searchContent" placeholder="请输入城市名称" @confirm="changeSearch(searchContent)" />
			</div> -->
			<uni-search-bar ref="search" maxlength="10" placeholder="请输入城市名称" @confirm="changeSearch" @clear="getBusStationList"
			 radius="80" bgColor="#fff" clearButton="always" cancelButton="none" />
		</div>

		<view class="history_list-wrap tp-w690" v-if="historyList.length">
			<view class="top">
				<view class="l-top">历史记录</view>
				<view class="r-top-wrap" @click="handleClearHistory">
					<view class="icon">
						<uni-icons type="trash" color="#999999" size="20"></uni-icons>
					</view>
					<view>清除历史</view>
				</view>
			</view>
			<view class="history_list">
				<view class="history_item" v-for="(it_h,in_h) in historyList" :key="in_h">
					<text @click="tagSrarch(it_h)">{{it_h.value}}</text>
					<view class="icon" @click.stop="handleClearHistoryItem(it_h.historyId,in_h)">
						<uni-icons type="closeempty" color="#999999"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<view class="location-wrap tp-w690">
			<view class="location_top">当前城市</view>
			<text class="location_address" @click="nowCity()">{{curLocation}}</text>
		</view>

		<view class="address-list">
			<view class="address-item" :class="{active: it_a.value.match(/[A-Z]/)}" :style="{paddingBottom: curAddressIndex===in_a&&it_a.sub?'0':'20rpx', 
						marginBottom: curAddressIndex===in_a&&it_a.sub?'20rpx':'0'
					}"
			 v-for="(it_a,in_a) in addressList" :key="in_a" @click.stop.prevent="handleChooseAddress(it_a, in_a)">
				<text>{{it_a.value}}</text>
				<view class="search-address-list" v-if="curAddressIndex===in_a">
					<view class="search-address-item" v-for="(it_s,in_s) in it_a.sub" :key="in_s" @click.stop.prevent="handleChooseAddressSub(it_s, in_a)">
						<text>{{it_s.value}}</text>
						<uni-icons type="circle-filled" color='#FFAF3C' size="24" v-if="it_s.choosed"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- <view v-if="choosedAddressInfo.value" class="confirm-btn" @click="handleConfirmChooseAddress">确定</view> -->
	</view>
</template>

<script>
	import searchMatch from '../../utils/searchMatch.js'
	import $DB from '../../utils/debounce.js'
	export default {
		components: {

		},
		data() {
			return {
				curLocation: '', // 当前地址
				travelsStatus: '', // to出发地选择 | form目的地选择
				goType: 'go', // 选择出发地go 	选择目的地 back
				stationId: '', // 已选择的地点id
				searchContent: '', // 	用户自主搜索的站名或者城市名
				historyList: [], // 搜索历史记录
				addressList: [],
				curAddressIndex: 0,
				choosedAddressInfo: {},
				searchedAddressList: [],
				loginNum: false,
				trlineid:0
			};
		},
		onLoad(opt) {
			let checkId = ''
			// console.log(opt)
			this.trlineid  = opt.trlineid;
			let obj = this.$store.getters.getHomeChoosedAddressObj
			this.travelsStatus = opt && opt.travelsStatus
			if (obj.from || obj.to) {
				if (this.travelsStatus == 'from') {
					this.goType = 'go'
					checkId = obj && obj.to && obj.to.id
					this.stationId = ''
				} else {
					this.goType = 'back'
					checkId = obj && obj.from && obj.from.id
					this.stationId = checkId
				}
			}
			uni.setStorageSync('goType', this.goType);
			this.getCurLocation()
			if (!this.$store.getters.getToken) {
				uni.navigateTo({
					url: './login'
				})
			}
		},
		onShow() {
			if (this.$store.getters.getToken) {
				this.updateSearchHistoryList() // 获取历史搜索站点记录
				this.getBusStationList()
			}
		},
		methods: {
			getCurLocation() {
				this.curLocation = this.$store.getters.getCurLocation.city
			},
			// 搜索
			changeSearch(e) { // 用户点击键盘上的搜索按钮时触发
				let str = e.detail && e.detail.value || e.value || e
				this.searchContent = str
				this.getBusStationList()
			},
			// 点击历史的标签
			tagSrarch(val) {
				// console.log(val);
				this.choosedAddressInfo = val
				this.handleConfirmChooseAddress()
			},
			// 点击现在的城市
			nowCity() {
				this.addressList.forEach((item, index) => {
					if (item.value == this.curLocation) {
						this.handleChooseAddress(item, index)
					}
				})
				this.scrollTo()
			},
			handleChooseAddress(item, i) {
				if (this.curAddressIndex == i && this.addressList[i].sub) {
					this.curAddressIndex = 0
					this.addressList[i].sub.forEach(it => {
						it.choosed = false
					})
					this.choosedAddressInfo = {}
				} else
				if (this.curAddressIndex !== i && this.addressList[i].sub) {
					this.addressList[i].sub.forEach(it => {
						it.choosed = false
					})
					this.curAddressIndex = i
					item.sub[0].choosed = true
					this.choosedAddressInfo = item.sub[0]
				}

			},
			// 选择地址
			handleChooseAddressSub(item, i) {
				this.addressList[i].sub.forEach(it => {
					it.choosed = false
				})
				item.choosed = true
				this.choosedAddressInfo = item
				this.handleConfirmChooseAddress()
			},
			// 清除全部
			handleClearHistory() {
				this.$http.get(this.$api.delSearchHistorys + '?type=2').then(res => {
					if (res.code == 200) { // 保存更新历史搜索记录
						this.updateSearchHistoryList()
					}
				})
			},
			// 删除单个历史
			handleClearHistoryItem(id, index) {
				// this.$store.commit('delSearchHistoryList', i)
				this.$http.get(this.$api.delSearchHistory + '?ids=' + id).then(res => {
					if (res.code == 200) { // 保存更新历史搜索记录
						this.updateSearchHistoryList()
					}
				})
			},
			// 确定选择地址
			handleConfirmChooseAddress() {

				if (this.travelsStatus) {
					this.$store.commit('upHomeChoosedAddressObj', {
						[this.travelsStatus]: this.choosedAddressInfo
					})
					uni.navigateBack({
						delta: 1
					})
				}
			},
			// 更新历史记录
			updateSearchHistoryList() {
				// this.historyList = this.$store.getters.getSearchHistoryList
				this.$http.get(this.$api.saveSearchHistory + '?type=2').then(res => {
					if (res.code === 200) {
						this.historyList = res.data.searchList
					}
				})
			},
			scrollTo() {
				uni.createSelectorQuery().select(".address-list").boundingClientRect(data => { //目标节点
					uni.createSelectorQuery().select(".search-address-list").boundingClientRect((res) => { //最外层盒子节点
						uni.pageScrollTo({
							duration: 0, //过渡时间必须为0，uniapp bug，否则运行到手机会报错
							scrollTop: res.top - data.top, //滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
						})
					}).exec()
				}).exec();
			},

			// 请求列表数据
			getBusStationList() {
				this.$http.get(this.$api.getBusStation, {
					type: 2,
					stationId: this.stationId,
					goType: this.goType,
					stationName: this.searchContent,
					regularType: this.trlineid
				}).then(res => {
					console.log(res)
					if (res.code === 200) {
						this.disposeData(res.data.cityMap)
						this.searchContent = ''
						// this.$refs.search.clear()
					}
				})
			},
			// 处理列表数据
			disposeData(data) {
				let arr = []
				let arr_tmp = []
				let cityMap = data
				let keys = Object.keys(data)
				keys.forEach(key => {
					for (let i = 0; i < cityMap[key].length; i++) {
						arr_tmp.push(key)
					}
				})
				keys.forEach(key => {
					cityMap[key].forEach(item => { // 首字母所包含的数据
						if (arr_tmp.includes(key)) {
							let city = Object.keys(item)[0]
							let obj = {
								label: city,
								value: city,
								sub: []
							}
							item[city].forEach(sub => {
								obj.sub.push({
									label: sub.value,
									value: sub.value,
									id: sub.id
								})
							})
							arr.push({
								label: key,
								value: key
							}, obj)
						}
					})
				})

				function uniq(arr) {
					var tmp = new Set(arr.map(item => JSON.stringify(item)));
					return Array.from(tmp).map(item => JSON.parse(item));
				}
				this.addressList = uniq(arr)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		padding-top: 104rpx;
		padding-bottom: 120rpx;
	}

	.search-wrap {
		background-color: #00B4FF;
		// padding: 12rpx 0;
		position: fixed;
		/* #ifdef MP-WEIXIN */
		top: 0;
		/* #endif */
		/* #ifdef H5 */
		top: 44px;
		/* #endif */
		left: 0;
		right: 0;
		z-index: 2;
		padding: 16rpx;

		.input {
			width: 690rpx;
			margin: 0 auto;
			height: 56rpx;
			line-height: 56rpx;
			border-radius: 28rpx;
			color: #CCCCCC;
			background: #fff url(../../static/imgs/icons/search-icon.png) no-repeat left 238rpx center;
			background-size: 28rpx 28rpx;
			padding-left: 275rpx;
			box-sizing: border-box;
		}
	}

	.history_list-wrap {
		.top {
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: #666;
			font-size: 26rpx;
			padding: 40rpx 0 20rpx;

			.r-top-wrap {
				display: flex;
				justify-content: flex-end;
				align-items: center;

				.icon {
					margin-top: 5rpx;
					margin-right: 20rpx;
				}
			}
		}

		.history_list {
			display: flex;
			flex-wrap: wrap;

			.history_item {
				font-size: 28rpx;
				padding: 19rpx 60rpx 19rpx 21rpx;
				background-color: #fff;
				border-radius: 8rpx;
				display: flex;
				margin: 0 20rpx 20rpx 0;
				position: relative;

				.icon {
					position: absolute;
					top: 50%;
					transform: translateY(-50%);
					right: 19rpx;
				}
			}
		}
	}

	.location-wrap {
		margin-bottom: 20rpx;

		.location_top {
			margin: 20rpx auto;
			text-align: left;
			font-size: 26rpx;
			color: #666;
		}

		.location_address {
			display: inline-block;
			font-size: 28rpx;
			padding: 19rpx 21rpx;
			background-color: #fff;
			border-radius: 8rpx;
		}
	}

	.address-list {
		.address-item {
			background-color: #fff;
			padding: 30rpx;
			border-bottom: 1px solid #f5f5f5;
			font-size: 30rpx;

			&.active {
				font-size: 36rpx;
				background-color: #f5f5f5;
			}
		}
	}

	.search-address-list {
		.search-address-item {
			background-color: #fff;
			padding: 0 30rpx;
			height: 92rpx;
			border-bottom: 1px solid #f5f5f5;
			font-size: 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			&:last-child {
				border: none;
			}

			&.active {
				font-size: 36rpx;
				background-color: #f5f5f5;
			}
		}
	}

	.confirm-btn {
		width: 750rpx;
		height: 98rpx;
		line-height: 98rpx;
		text-align: center;
		background: $blue;
		font-size: 32rpx;
		color: #fff;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
	}
</style>
